<template>
  <div>
    <div class="operate">
      <el-button link type="primary" @click="operateRow('add')" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: #ff9900;
            color: rgba(255, 255, 255, 1);
          ">新增</el-button>
      <el-form @submit.prevent="getLeaderManage">
        <el-form-item label="姓名" style="margin-right: 15px;margin-left: 13px;">
          <el-input v-model="name" placeholder="" @keyup.enter="getLeaderManage" style="width: 200px" />
        </el-form-item>
      </el-form>
      <el-button @click="getLeaderManage" class="btn btnsearch">查询</el-button>
      <el-button @click="handleReset" class="btn btnreset">重置</el-button>
    </div>
    <div class="mt-0">
      <el-table v-loading="loading" element-loading-text="Loading..." :data="tableData" :header-cell-style="headerCellStyle" style="width: 100%" row-key="id"
        height="calc(100vh - 260px)" default-expand-all>
        <el-table-column prop="name" label="姓名" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <div class="namecont">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="类型" align="center" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="namecont">
              {{ leaderTypeObj[row.category] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" min-width="120">
          <template #default="{ row }">
            {{ sexTypeObj[row.sex] }}
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="联系电话" align="center" min-width="180" />
        <el-table-column prop="title" label="职务" align="center" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <div class="namecont">
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="schedule" label="值班时间" align="center" min-width="320" show-overflow-tooltip>
          <template #default="scope">
            <div class="namecont">
              {{ scope.row.schedule }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" min-width="140">
          <template #default="{ row }">
            <el-button type="primary" link @click="operateRow('edit', row)">编辑</el-button>
            <el-button type="primary" link @click="operateRow('del', row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex mt-16">
        <el-pagination class="ml-auto" :hide-on-single-page="value" v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100]" :total="total" @current-change="handleCurrentChange" @size-change="selectchange"
          layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </div>
    <el-dialog :title="dialogTitle" v-model="operateVisible" width="50%" destroy-on-close>
      <DynamicForm ref="dynamicForm" :formObj="state.formData" :formItemList="formItemList" :rules="state.rules"
        autoRules />
      <template #footer>
        <span>
          <el-button @click="operateVisible = false">取消</el-button>
          <el-button type="warning" @click="submitPartyOrganization">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
import leaderManageApi from '@/api/spb/organizationManage/leaderManage'
import globalApi from '@/api/spb/global'
import DynamicForm from '../../components/DynamicForm.vue'

const dynamicForm = ref()
const message = useMessage()
const operateVisible = ref(false)
const dialogTitle = ref('')
const tableData = ref([])
const residentList = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const name = ref('')
const loading = ref(true) // 列表加载中
const value = ref(true)
const state = reactive({
  formData: {},
  rules: {
    name: [{ required: true, message: '姓名不能为空！', trigger: 'change' }],
    category: [{ required: true, message: '类型不能为空！', trigger: 'change' }],
    sex: [{ required: true, message: '性别不能为空！', trigger: 'change' }],
    idNumber: [
      { required: true, message: '身份证号不能为空！', trigger: 'blur' },
      {
        pattern:
          /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        message: '请输入正确的身份证号码',
        trigger: 'blur'
      }
    ],
    telephone: [
      { required: true, message: '联系电话不能为空！', trigger: 'blur' },
      {
        pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    title: [{ required: true, message: '职务不能为空！', trigger: 'blur' }]
  }
})
const formItemList = computed(() => {
  return [
    {
      label: '姓名',
      name: 'name',
      require: true,
      type: 'select',
      labelFiled: 'name',
      valueFiled: 'name',
      options: residentList.value
    },
    {
      label: '类型',
      name: 'category',
      require: true,
      type: 'select',
      options: [
        {
          label: '值班领导',
          value: 0
        },
        {
          label: '代班领导',
          value: 1
        }
      ]
    },
    {
      label: '性别',
      name: 'sex',
      require: false,
      type: 'radioGroup',
      labelFiled: 'name',
      valueFiled: 'id',
      options: [
        {
          id: 1,
          name: '男'
        },
        {
          id: 2,
          name: '女'
        }
      ]
    },
    {
      label: '身份证号',
      name: 'idNumber',
      require: true,
      type: 'input'
    },
    {
      label: '联系电话',
      name: 'telephone',
      require: true,
      type: 'input'
    },
    {
      label: '职务',
      name: 'title',
      require: true,
      type: 'input'
    },
    {
      label: '值班时间',
      name: 'schedule',
      require: false,
      type: 'checkboxGroup',
      options: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    {
      label: '照片',
      name: 'photoUrl',
      require: false,
      type: 'uploadImg'
    }
  ]
})

const sexTypeObj = {
  1: '男',
  2: '女'
}

const leaderTypeObj = {
  0: '值班领导',
  1: '代班领导'
}

/** 条数变化 */
const selectchange = (e) => {
  pageSize.value = e
  currentPage.value = 1
  getLeaderManage()
}
/** 页码变化 */
const handleCurrentChange = (e) => {
  currentPage.value = e
  getLeaderManage()
}

const headerCellStyle = computed(() => {
  return { background: '#f0f0f0' }
})

// 获取党员信息
function getResidentList() {
  globalApi.getPartyList().then((res) => {
    residentList.value = res
  })
}

// 获取领导班子列表
function getLeaderManage() {
  const data = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    name: name.value
  }
  leaderManageApi.operateLeaderManage('page', data, null).then((res) => {
    tableData.value = res.list
    total.value = res.total
    if (tableData.value.length === 0) {
            value.value = true
        } else {
            value.value = false
        }
        loading.value = false
  }).catch(error => {
        loading.value = false
    })
}

// 字段映射
const typeRelate = (item) => {
  let content = ''
  residentList.value.forEach((t) => {
    if (t.name == item) {
      content = t.id
    }
  })
  return content
}

// 新增/编辑领导班子
async function submitPartyOrganization() {
  dynamicForm.value.validateForm(() => {
    let data = dynamicForm.value.getFormData()
    data.partyMemberId = typeRelate(data.name)
    data.schedule = data.schedule?.join('、')
    const type = dialogTitle.value.includes('新增') ? 'create' : 'update'
    leaderManageApi.operateLeaderManage(type, data, null).then(() => {
      getLeaderManage()
      operateVisible.value = false
      message.success(`${dialogTitle.value}成功`)
    })
  })
}

// 删除领导班子
function delPartyOrganization(row) {
  const params = {
    ids: row.id
  }
  ElMessageBox.confirm(`确认删除【${row.name}】吗`, '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  }).then(() => {
    leaderManageApi.operateLeaderManage('delete', null, params).then(() => {
      getLeaderManage()
      operateVisible.value = false
      message.success(`删除${row.name}成功`)
    })
  })
}

// 表格操作
function operateRow(type, row) {
  if (type === 'del') {
    delPartyOrganization(row)
    return
  }
  state.formData = type === 'add' ? {} : row
  if (typeof state.formData.schedule === 'string') {
    state.formData.schedule = state.formData.schedule?.split('、')
  }
  if (state.formData.schedule === null) {
    state.formData.schedule = []
  }
  dialogTitle.value = `${type === 'add' ? '新增' : '编辑'}`
  operateVisible.value = true
}

// 重置操作
function handleReset() {
  currentPage.value = 1
  pageSize.value = 20
  name.value = ''
  getLeaderManage()
}

onMounted(() => {
  getLeaderManage()
  getResidentList()
})
</script>

<style lang="scss" scoped>
@import url('../../styles/global.css');

.operate {
  display: flex;
}

.btn {
  width: 80px;
  height: 30px;
  line-height: 20px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.btnreset {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  color: rgba(142, 142, 142, 1);
}

.btnsearch {
  background-color: #cc352f;
  color: rgba(255, 255, 255, 1);
  border: 1px solid #cc352f;
}

.btn:hover {
  opacity: 0.8;
}

.btnhover:hover {
  opacity: 0.8;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #cc352f;
}
.namecont {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
